package com.npsngs.hawkeye;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.Log;
import android.view.MotionEvent;

public class MyGLSurfaceView extends GLSurfaceView {
	private MyRenderer mRenderer;
	private static final int SCROLL_ACTION  = 1;
	private static final int SCALE_ACTION  = 2;
	public MyGLSurfaceView(Context context) {
		super(context);
		mRenderer = new MyRenderer();
		setRenderer(mRenderer);
	}

	private float downX = -1;
	private float downY = -1;
	private float delta = -1;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		Log.d("Action:"+event.getAction(), "x:"+event.getX()+" y:"+event.getY());
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			downX = event.getX();
			downY = event.getY();
			break;
		case MotionEvent.ACTION_UP:
			nativeActCancel(SCROLL_ACTION);
			break;
		case MotionEvent.ACTION_POINTER_UP:
		case MotionEvent.ACTION_POINTER_2_UP:
			downX = -1;
			downY = -1;
			delta = -1;
			nativeActCancel(SCALE_ACTION);
			break;
		case MotionEvent.ACTION_MOVE:
			int pc = event.getPointerCount();
			if(pc > 1){
				float dx = event.getX(1)-event.getX(0);
				float dy = event.getY(1)-event.getY(0);
				float centerX = (event.getX(1) + event.getX(0))/2;
				float centerY = (event.getY(1) + event.getY(0))/2;
				if(delta > 0){
					float newDelta = (float) Math.sqrt(dx*dx+dy*dy);
					float ratio = newDelta/delta;
					nativeOnScale(ratio,ratio,centerX,centerY);
				}else{
					
					delta = (float) Math.sqrt(dx*dx+dy*dy);
				}
			}else{
				if(downX < 0 || downY <0){
					break;
				}
				float deltaX = event.getX()-downX;
				float deltaY = event.getY()-downY;
				nativeOnScroll(deltaX, deltaY);
			}
			break;
		}
		return true;
	}

	class MyRenderer implements GLSurfaceView.Renderer {
		public void onSurfaceCreated(GL10 gl, EGLConfig config) {
			nativeInit();
		}

		public void onSurfaceChanged(GL10 gl, int w, int h) {
			nativeResize(w, h);
		}

		public void onDrawFrame(GL10 gl) {
			nativeRender();
		}
	}
	
	private static native void nativeActCancel(int actionType);
	private static native void nativeOnScroll(float distanceX, float distanceY);
	private static native void nativeOnScale(float scaleX, float scaleY,float centerX,float centerY);
	public static native void nativeGLReset();
	
	private static native void nativeInit();

	private static native void nativeResize(int w, int h);

	private static native void nativeRender();

	private static native void nativeDone();
}